package com.wsdcd.zlg.sb.controller;

import com.wsdcd.zlg.sb.model.entity.User;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping()
    public String list(){
        return "upload/upload";
    }

    @PostMapping("file")
    public String upload(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            // 为空就不搭理了
            return "error";
        }
        // 说明上传了
        // getRealPath 获取指定目录的绝对路径,比如 E:/xxx/xx/xx 找的是TomCat下的路径,不是工作空间
        // 重新编译后就消失了
        String realpath = request.getServletContext().getRealPath("/resources/upload");
        // E:\SortWare\Work\apache-tomcat-7.0.93\webapps\SpringMVC_02_User\resources\
        // upload/
        // System.out.println(realpath);
        // getOriginalFilename 获取文件名和后缀名
        File destFile = new File(realpath + "/"
                + System.currentTimeMillis() + file.getOriginalFilename());
        // org.apache.commons.io.FileUtils
        try {
            // 第一个参数是文件源的流
            // 第二个参数是到哪去
            FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
